'use strict';

const db = uniCloud.database()
const uniIdCommon = require('uni-id-common')

exports.main = async (event, context) => {
  // 1. 验证管理员身份
  const token = context.uniIdToken || event.uniIdToken
  if (!token) {
    return { code: 401, msg: '未登录' }
  }
  
  const uniId = uniIdCommon.createInstance({ context })
  const tokenRes = await uniId.checkToken(token)
  if (tokenRes.code !== 0) {
    return { code: 401, msg: 'token无效或已过期' }
  }

  const { refundIds, action, reason, adminId } = event
  
  if (!refundIds || !Array.isArray(refundIds) || refundIds.length === 0) {
    return { code: 400, msg: '退款ID列表不能为空' }
  }

  if (!action || !['approve', 'reject'].includes(action)) {
    return { code: 400, msg: '操作类型无效' }
  }

  if (action === 'reject' && !reason) {
    return { code: 400, msg: '拒绝退款必须提供理由' }
  }

  try {
    const refundCollection = db.collection('refund_records')
    const auditLogCollection = db.collection('audit_logs')
    const messageCollection = db.collection('system_messages')
    
    let successCount = 0
    let failCount = 0
    const results = []

    // 批量处理每个退款申请
    for (const refundId of refundIds) {
      try {
        // 获取退款记录
        const refundResult = await refundCollection.doc(refundId).get()
        if (!refundResult.data || refundResult.data.length === 0) {
          results.push({ refundId, success: false, error: '退款记录不存在' })
          failCount++
          continue
        }

        const refund = refundResult.data[0]
        
        // 检查退款状态
        if (refund.status !== 'processing') {
          results.push({ refundId, success: false, error: '只能处理待处理状态的退款' })
          failCount++
          continue
        }

        if (action === 'approve') {
          // 批准退款
          await refundCollection.doc(refundId).update({
            status: 'success',
            processed_time: new Date(),
            admin_id: adminId || 'admin'
          })

          // 如果是钱包支付，退回用户余额
          if (refund.payment_info && refund.payment_info.payment_method === 'wallet') {
            try {
              await uniCloud.callFunction({
                name: 'userPointsManager',
                data: {
                  action: 'add',
                  userId: refund.user_id,
                  amount: refund.amount,
                  type: 'refund',
                  description: `批量退款：${reason || '管理员批准'}`,
                  relatedId: refundId
                }
              })
            } catch (balanceError) {
              console.error('余额退回失败:', balanceError)
            }
          }

          // 发送通知
          await messageCollection.add({
            user_id: refund.user_id,
            type: 'refund',
            title: '退款成功通知',
            content: `您的退款申请已批准，金额 ¥${refund.amount} 已退回您的账户。`,
            create_time: new Date(),
            read: false
          })

        } else if (action === 'reject') {
          // 拒绝退款
          await refundCollection.doc(refundId).update({
            status: 'failed',
            processed_time: new Date(),
            admin_id: adminId || 'admin',
            error_message: reason
          })

          // 发送通知
          await messageCollection.add({
            user_id: refund.user_id,
            type: 'refund',
            title: '退款申请被拒绝',
            content: `您的退款申请已被拒绝，原因：${reason}`,
            create_time: new Date(),
            read: false
          })
        }

        // 记录审计日志
        await auditLogCollection.add({
          target_type: 'refund',
          target_id: refundId,
          action: action,
          reason: reason || `批量${action === 'approve' ? '批准' : '拒绝'}退款`,
          admin_id: adminId || 'admin',
          create_time: new Date(),
          extra_info: {
            amount: refund.amount,
            batch_operation: true
          }
        })

        results.push({ refundId, success: true })
        successCount++

      } catch (error) {
        console.error(`处理退款 ${refundId} 失败:`, error)
        results.push({ refundId, success: false, error: error.message })
        failCount++
      }
    }

    return {
      code: 200,
      msg: `批量处理完成，成功 ${successCount} 个，失败 ${failCount} 个`,
      data: {
        successCount,
        failCount,
        results
      }
    }

  } catch (error) {
    console.error('批量处理退款失败:', error)
    return {
      code: 500,
      msg: '批量处理失败',
      data: null
    }
  }
}
